<script setup lang="ts">
import {h, ref} from 'vue';
import {Button, Dropdown, Menu, MenuItem, message, Modal as AntModal, Space, Tag} from 'ant-design-vue';
import {ColPage} from '#/components/common-ui';
import {useModal, useVxeGrid} from '#/ui-kit';
import {useDictStore} from '#/stores';
import dayjs from 'dayjs';

import {findUserListPage, removeUserInfo, userResetPassword} from '#/api/system/user';

import UserChangeModal from './user-change-modal.vue';
import DeptTree from "./dept-tree.vue";

const selectDeptId = ref([]);

const {getDictData} = useDictStore();

const [Grid, gridApi] = useVxeGrid({
  tableTitle: '用户列表',
  gridOptions: {
    columns: [
      {fixed: 'left', title: '#', type: 'seq', minWidth: 50},
      {fixed: 'left', field: 'nickname', title: '用户姓名', minWidth: 120,},
      {field: 'username', title: '用户账号', minWidth: 120,},
      {
        slots: {
          default: ({row}) => {
            const data = getDictData('enable_status', true).find(item => item.value === row.enableStatus);
            return h(Tag, {color: data?.color || 'default'}, () => data?.label || '未知');
          }
        }, title: '启用状态', minWidth: 80,
      },
      {
        field: 'lastLoginTime', title: '最后登陆', minWidth: 180, formatter: ({cellValue}) => {
          return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '-';
        }
      },
      {field: 'createTime', title: '创建时间', formatter: 'formatDateTime', minWidth: 180},
      {fixed: 'right', slots: {default: 'action'}, title: '操作', minWidth: 180},
    ],
    proxyConfig: {
      ajax: {
        query: async ({page}) => {
          return await getUserListPage({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...gridApi?.formApi?.form?.values,
          });
        }
      }
    },
    stripe: true,
    keepSource: true,
    height: 'auto',
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  },
  formOptions: {
    commonConfig: {
      componentProps: {
        allowClear: true,
      },
    },
    schema: [
      {
        label: '用户姓名',
        fieldName: 'nickname',
        component: 'Input',
        componentProps: {
          placeholder: '请输入用户姓名'
        }
      },
      {
        label: '用户账号',
        fieldName: 'username',
        component: 'Input',
        componentProps: {
          placeholder: '请输入用户账号'
        }
      },
      {
        label: '启用状态',
        fieldName: 'enableStatus',
        component: 'Select',
        componentProps: {
          options: getDictData('enable_status', true),
          placeholder: '请选择启用状态'
        }
      },
    ],
    showCollapseButton: true,
    collapsed: true,
    handleReset: async () => {
      selectDeptId.value = [];
      await gridApi?.formApi?.resetForm();
      await gridApi?.reload();
    }
  }
});

const [Modal, modalApi] = useModal({
  class: 'w-[750px]',
  connectedComponent: UserChangeModal,
});

const getUserListPage = (params: any) => {
  return new Promise<{ items: any; total: number }>((resolve) => {
    findUserListPage({
      ...params,
      deptId: selectDeptId.value?.length > 0 ? selectDeptId.value[0] : null
    }).then(res => {
      resolve({
        items: res.records,
        total: res.totalRow,
      });
    }).catch(() => {
      resolve({
        items: [],
        total: 0
      });
    })
  });
};

const handleCreateUser = () => {
  modalApi.setState({title: '新增用户'});
  modalApi.open();
}

const handleUpdateUser = (row) => {
  modalApi.setState({title: '更新用户'});
  modalApi.setData(row);
  modalApi.open();
}

const handleRemoveUser = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否删除当前用户',
    centered: true,
    async onOk() {
      await removeUserInfo(row.id).then(() => {
        gridApi.reload();
        message.success('用户信息删除成功');
      });
    }
  });
}

const handleResetPassword = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否重置当前用户密码',
    centered: true,
    async onOk() {
      await userResetPassword(row.id).then(() => {
        gridApi.reload();
        message.success('用户密码重制成功');
      });
    }
  });
}
</script>

<template>
  <ColPage auto-content-height :left-width="20" :right-width="80">
    <template #left>
      <DeptTree v-model:select-dept-id="selectDeptId"
                @select="() => gridApi.reload()"
      />
    </template>
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" v-access:code="['sys:user:create']" @click="handleCreateUser()">新增用户</Button>
        </Space>
      </template>

      <template #action="{ row }">
        <Button type="link" size="small" v-access:code="['sys:user:update']" @click="handleUpdateUser(row)">编辑
        </Button>

        <Button type="link" size="small" v-access:code="['sys:user:remove']" @click="handleRemoveUser(row)">删除
        </Button>

        <Dropdown :trigger="['click']">
          <Button type="link" size="small" v-access:code="['sys:user:password-reset']">更多</Button>
          <template #overlay>
            <Menu>
              <div v-access:code="['sys:user:password-reset']">
                <MenuItem @click="handleResetPassword(row)">重置密码</MenuItem>
              </div>
            </Menu>
          </template>
        </Dropdown>
      </template>
    </Grid>

    <Modal @close="() => gridApi.reload()"/>
  </ColPage>
</template>